package no.kolstad.movies.controller;

import java.util.HashSet;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import no.kolstad.movies.dao.RoleDAO;
import no.kolstad.movies.dao.UserDAO;
import no.kolstad.movies.model.Role;
import no.kolstad.movies.model.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

/**
* Copyright 2008 Christopher Kolstad.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* under the License.

/***
 * @author chriswk - Christopher Kolstad
 */
 
public class RegisterUserController extends SimpleFormController {
      private UserDAO uDao;
  private RoleDAO rDao;

  public void setUserDAO(UserDAO dao) {
    this.uDao = dao;
  }

  public void setRoleDAO(RoleDAO dao) {
    this.rDao = dao;
  }

  protected Log log = LogFactory.getLog(this.getClass());

  protected Object formBackingObject(HttpServletRequest request)
      throws Exception {

    if (log.isInfoEnabled()) {
      log.info("EditUserFormController formBackingObject");
    }

    if (request.getParameter("id") != null
        && !"".equals(request.getParameter("id"))) {
      Long id = Long.parseLong(request.getParameter("id"));
      User existingUser = uDao.get(id);
      if (log.isDebugEnabled()) {
        log.debug("Fetched user: " + existingUser.toString());
      }
      return existingUser;
    }

    return new User();
  }

  public ModelAndView onSubmit(HttpServletRequest request,
      HttpServletResponse response, Object command, BindException errors)
      throws ServletException {
    User newuser = (User) command;
    Set<Role> roles = new HashSet<Role>();
    roles.add(rDao.getRole("ROLE_USER"));
    newuser.setRoles(roles);
    uDao.save(newuser);

    request.getSession().setAttribute("statusMessage", "User saved");

    return new ModelAndView(new RedirectView(getSuccessView()));
  }


}
